package esb.chapter11.scubadiving.servicemix;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.xml.transform.Source;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;

import esb.chapter11.scubadiving.bean.LunchIF;
import esb.chapter11.scubadiving.model.LunchBooking;
import esb.util.framework.JiBXUtil;

public class LunchService extends ComponentSupport implements MessageExchangeListener {
	
	private final static Logger logger = Logger.getLogger(LunchService.class);
	@Resource
	private DeliveryChannel channel;
	private LunchIF lunch;
	
    public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	if (exchange.getStatus() != ExchangeStatus.ACTIVE) {
    		logger.info("state is not active so ignoring call");
    		return;
    	}
    	LunchBooking lunchBooking = null;
    	try {
    		Source contentSource = getInMessage(exchange).getContent();
    		lunchBooking = (LunchBooking) JiBXUtil.unmarshalDocument(
    				contentSource, LunchBooking.class);
        } catch(Exception e) {
        	logger.error("error while reading payload", e);
        }
        lunch.processLunch(lunchBooking);
        exchange.setStatus(ExchangeStatus.DONE);
        channel.send(exchange);
    }

	public void setLunch(LunchIF lunch) {
		this.lunch = lunch;
	}
}
